package com.arm.core.interceptor;

import com.arm.module.InterfaceConfig;
import com.arm.module.base.BaseModule;
import com.arm.service.InterfaceConfigService;
import com.arm.tools.MD5Tools;
import com.arm.tools.myRunTime.MyRunTimeExcption;
import com.arm.tools.result.ResultObj;
import com.arm.tools.result.ReturnCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Andrew  on 2016/12/29.
 */
@Component
public class AuthorityInterceptor implements HandlerInterceptor {

    public <T> T getService(Class<T> clazz, HttpServletRequest request) {
        //通过该方法获得的applicationContext 已经是初始化之后的applicationContext 容器
        WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        return applicationContext.getBean(clazz);
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");

        HttpSession session = httpServletRequest.getSession();
        System.out.println("jingru==========================>>>>>>>>>>>>>>>>>>");

        InterfaceConfigService interfaceConfigService = getService(InterfaceConfigService.class, httpServletRequest);
        String sign = httpServletRequest.getHeader("sign");
        String timestamp = httpServletRequest.getHeader("timestamp");
        String apiId = httpServletRequest.getHeader("APIID");
        System.out.println(timestamp + "jingru==========================>>>>>>>>>>>>>>>>>>" + sign);
        ResultObj resultObj = new ResultObj();
        try {

if(StringUtils.isBlank(sign)){
    throw new MyRunTimeExcption(ReturnCode.FAIL);
}
        if(   sign.equals((String)session.getAttribute("sign"))){
            System.out.println("jingru====================放过，xiesesion======>>>>>>>>>>>>>>>>>>");
            return true;
        }




            InterfaceConfig interfaceConfig = interfaceConfigService.selectInterfaceConfigById(Long.parseLong(apiId));
            if (interfaceConfig == null) {
                throw new MyRunTimeExcption(ReturnCode.FAIL);
            }


            Byte status = interfaceConfig.getStatus();
            if (status.byteValue() != BaseModule.STATUS_VALID) {
                throw new MyRunTimeExcption(ReturnCode.FAIL);
            }
            String appCode = interfaceConfig.getAppCode();
           if(!sign.toUpperCase().equals(MD5Tools.saltEncryption(appCode+timestamp))){
               throw new MyRunTimeExcption(ReturnCode.FAIL);
           }


           session.setAttribute("sign",sign);
            return true;
        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
            resultObj.setCode(myRunTimeExcption.getErroCode());
            resultObj.setMsg(myRunTimeExcption.getMessage());
            System.out.println(resultObj.toJson());
            try {
                httpServletResponse.getWriter().write(resultObj.toJson().toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("jingru====================fanhuifail======>>>>>>>>>>>>>>>>>>" + resultObj.toJson());
        } catch (NumberFormatException e) {
            e.printStackTrace();

        }  catch (Exception e) {
            e.printStackTrace();
        }

        return false;

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
